package com.ease.framework.gef4p.commands {
   import com.ease.framework.gef.IEditor;
   import com.ease.framework.gef4p.editparts.EdgeEditPart;
   import com.ease.framework.gef4p.editparts.NodeEditPart;
   import com.ease.framework.gef4p.editparts.PoolEditPart;
   import com.ease.framework.gef4p.model.Edge;
   import com.ease.framework.gef4p.model.Pool;
   import com.ease.framework.workbench.Workbench;
   import com.ease.framework.workbench.spi.impls.Command;

   public class RemoveEdgeCommand extends Command {
      protected var pool:Pool;

      protected var nowEdge:Edge;

      protected var tranEP:EdgeEditPart;

      public function RemoveEdgeCommand(edge:Edge) {
         super();
         nowEdge = edge;
         pool = nowEdge.pool;
      }

      override public function execute():void {
         if (tranEP == null) {
            tranEP = IEditor(Workbench.instance.currentEditor).getEditDomain().getEditPartByModel(nowEdge) as EdgeEditPart;
         }
         if (tranEP == null)
            return;
         if (tranEP.getSource() != null)
            tranEP.getSource().removeOutEdge(tranEP);
         if (tranEP.getTarget() != null)
            tranEP.getTarget().removeInEdge(tranEP);

         var processEditPart:PoolEditPart = IEditor(Workbench.instance.currentEditor).getEditDomain().getEditPartByModel(pool) as PoolEditPart;

         processEditPart.removeEdgeEditPart(tranEP);

         tranEP.remove();

         nowEdge.source.removeOutEdge(nowEdge); // outTransitions.removeItemAt( nowEdge.source.outTransitions.getItemIndex( nowEdge ));
         nowEdge.target.removeInEdge(nowEdge); // inTransitions.removeItemAt( nowEdge.target.inTransitions.getItemIndex( nowEdge ));
         pool.removeEdge(nowEdge);
      }

      override public function undo():void {

         var sourceEP:NodeEditPart = IEditor(Workbench.instance.currentEditor).getEditDomain().getEditPartByModel(nowEdge.source) as NodeEditPart;
         var targetEP:NodeEditPart = IEditor(Workbench.instance.currentEditor).getEditDomain().getEditPartByModel(nowEdge.target) as NodeEditPart;
         if (sourceEP == null || targetEP == null)
            return;

         pool.addEdge(nowEdge);

         if (tranEP == null)
            tranEP = IEditor(Workbench.instance.currentEditor).getEditPartFactory().createEditPart(nowEdge) as EdgeEditPart;

         tranEP.unremove();

         tranEP.setSource(sourceEP);
         tranEP.setTarget(targetEP);

         var processEditPart:PoolEditPart = IEditor(Workbench.instance.currentEditor).getEditDomain().getEditPartByModel(pool) as PoolEditPart;
         processEditPart.addEdgeEditPart(tranEP);
      }
   }
}